<template>
  <div style="margin-top: 50px">
    <el-form
      :model="value"
      ref="productInfoForm"
      label-width="160px"
      class="form-inner-container"
      size="small"
    >
      <el-form-item label="名称：" prop="skuName">
        <el-input v-model="value.skuName"></el-input>
      </el-form-item>
      <el-form-item label="服务区域：" prop="areaId">
        <el-select
          v-model="value.areaId"
          placeholder="请选择服务区域"
          style="width: 100%"
        >
          <el-option
            v-for="item in areaOptions"
            :key="item.id"
            :label="item.areaName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="健康告知pdf文件：" prop="healthNoticeUrl">
        <upload
          :multiple="false"
          v-model="value.healthNoticeUrl"
          accept=".pdf"
          list-type="text"
        />
      </el-form-item>
      <el-form-item label="服务医院：" prop="hospitalIds">
        <select-scroll
          v-model="value.hospitalIds"
          keyword-name="name"
          :api="fetchHospitals"
          :multiple="true"
          :option="{
            label: 'hospitalName',
            value: 'id',
          }"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="购买份数上限：" prop="purchaseLimitNum">
        <el-input-number
          v-model="value.purchaseLimitNum"
          :controls="false"
          style="width: 100%"
        ></el-input-number>
      </el-form-item>

      <el-form-item label="价格设置：">
        <el-card shadow="never" class="cardBg">
          <div>
            年龄段：<el-button
              size="mini"
              class="littleMarginLeft"
              @click="ageDialogVisible = true"
              >增加</el-button
            >
            <el-checkbox-group
              v-model="ageListSelection"
              @change="handleUpdateSkus"
            >
              <div
                v-for="(item, index) in ageList"
                :key="formatAgeRange(item)"
                style="display: inline-block"
                class="littleMarginLeft"
              >
                <el-checkbox :label="JSON.stringify(item)">{{
                  formatAgeRange(item)
                }}</el-checkbox>
                <el-button
                  type="text"
                  class="littleMarginLeft"
                  @click="handleDeleteAgeItem(index, item)"
                  >删除
                </el-button>
              </div>
            </el-checkbox-group>
          </div>
          <div>
            缴费方式：
            <div>
              <el-checkbox-group
                v-model="paymentMethodSelected"
                @change="handleUpdateSkus"
              >
                <el-checkbox
                  v-for="item in paymentOptions"
                  :label="item.value"
                  :key="item.value"
                  class="littleMarginLeft"
                  >{{ item.label }}</el-checkbox
                >
              </el-checkbox-group>
            </div>
          </div>
        </el-card>
        <el-table
          ref="ageTableRef"
          style="width: 100%; margin-top: 20px"
          :data="value.pmsSkuPrices"
          highlight-current-row
          border
        >
          <el-table-column label="年龄段" align="center">
            <template slot-scope="scope">
              {{ formatAgeRange(scope.row) }}
            </template>
          </el-table-column>
          <el-table-column label="缴费方式" align="center">
            <template slot-scope="scope">
              {{ paymentMethods.getValue(scope.row.paymentMethod) }}
            </template>
          </el-table-column>
          <el-table-column label="购买价格(元)" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.price"
                :controls="false"
              ></el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item style="text-align: center">
        <el-button type="primary" size="medium" @click="handleSave"
          >提交</el-button
        >
      </el-form-item>
    </el-form>

    <el-dialog title="添加年龄段" :visible.sync="ageDialogVisible">
      <el-form ref="ageFormRef" :model="ageForm" :rules="ageFormRules">
        <el-row style="display: flex">
          <el-form-item label="起始年龄：" required label-width="100px">
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item prop="startPurchaseAge">
                <!--开始年龄-->
                <el-input-number
                  v-model="ageForm.startPurchaseAge"
                  :controls="false"
                ></el-input-number>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item prop="startUnit">
                <el-select v-model="ageForm.startUnit" placeholder="请选择类型">
                  <el-option
                    v-for="item in dateUnitOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="Number(item.value)"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>
        <el-row style="display: flex">
          <el-form-item label="结束年龄：" required label-width="100px">
          </el-form-item>
          <el-form-item>
            <!--结束年龄-->
            <el-row>
              <el-col :span="12">
                <el-form-item prop="endPurchaseAge">
                  <el-input-number
                    v-model="ageForm.endPurchaseAge"
                    :controls="false"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="endUnit">
                  <el-select v-model="ageForm.endUnit" placeholder="请选择类型">
                    <el-option
                      v-for="item in dateUnitOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="Number(item.value)"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="ageDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddSkuAge">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SingleUpload from "@/components/Upload/singleUpload.vue";
import {
  dateUnits,
  paymentMethods,
  ageUnits,
  paymentMethodEnum,
} from "@/utils/constant/pms";
import areasMixin from "@/mixins/areas";
import SelectScroll from "@/components/SelectScroll.vue";
import { fetchHospitals } from "@/api/common";
import Upload from "@/components/Upload/index.vue";
import { convertToYears } from "@/utils/date";
import { sortPmsSkuPriceByAge } from "@/utils/pms";

const initAgeForm = {
  startPurchaseAge: undefined,
  startUnit: ageUnits.day,
  endPurchaseAge: undefined,
  endUnit: ageUnits.year,
};

export default {
  name: "ProductInfoDetail",
  components: { Upload, SelectScroll, SingleUpload },
  props: {
    value: Object,
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  mixins: [areasMixin],
  data() {
    return {
      dateUnits,
      paymentMethods,
      dateUnitOptions: dateUnits.toKeyValueArray(),
      paymentOptions: [...paymentMethods.toKeyValueArray()],
      hasEditCreated: false,
      rules: {
        skuName: [{ required: true, message: "请输入名称", trigger: "blur" }],
        hospitalIds: [
          { required: true, message: "请选择服务医院", trigger: "blur" },
        ],
        productCategoryId: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
        brandId: [
          { required: true, message: "请选择商品品牌", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入商品介绍", trigger: "blur" },
        ],
        requiredProp: [
          { required: true, message: "该项为必填项", trigger: "blur" },
        ],
      },
      ageDialogVisible: false,
      ageForm: {
        ...initAgeForm,
      },
      ageFormRules: {
        startPurchaseAge: [
          { required: true, message: "请输入起始年龄", trigger: "blur" },
        ],
        startUnit: [
          { required: true, message: "请选择起始年龄单位", trigger: "blur" },
        ],
        endPurchaseAge: [
          { required: true, message: "请输入结束年龄", trigger: "blur" },
        ],
        endUnit: [
          { required: true, message: "请输入结束年龄单位", trigger: "blur" },
        ],
      },
      checkList: ["选中且禁用", "复选框 A"],
      paymentMethodSelected: [],
      ageListSelection: [],
      ageList: [],
    };
  },
  methods: {
    formatAgeRange(item) {
      return `${item.startPurchaseAge}${dateUnits.getValue(item.startUnit)}-${
        item.endPurchaseAge
      }${dateUnits.getValue(item.endUnit)}`;
    },
    fetchHospitals,
    setInitialData() {
      // 初始化数据
      let hasPeriod = false,
        hasSingle = false;
      this.value.pmsSkuPrices.forEach((item) => {
        const {
          startPurchaseAge,
          startUnit,
          endPurchaseAge,
          endUnit,
          paymentMethod,
        } = item;

        if (paymentMethod === paymentMethodEnum.period) {
          hasPeriod = true;
        } else if (paymentMethod === paymentMethodEnum.single) {
          hasSingle = true;
        }

        const isHaved =
          this.ageList.findIndex(
            (item) =>
              item.startPurchaseAge === startPurchaseAge &&
              item.endPurchaseAge === endPurchaseAge &&
              item.startUnit === startUnit &&
              item.endUnit === endUnit,
          ) > -1;
        if (!isHaved) {
          this.ageListSelection.push(
            JSON.stringify({
              startPurchaseAge,
              startUnit,
              endPurchaseAge,
              endUnit,
            }),
          );
          this.ageList.push({
            startPurchaseAge,
            startUnit,
            endPurchaseAge,
            endUnit,
          });
        }
      });

      if (hasPeriod && hasSingle) {
        this.paymentMethodSelected = [
          paymentMethodEnum.period,
          paymentMethodEnum.single,
        ];
      } else if (hasPeriod) {
        this.paymentMethodSelected = [paymentMethodEnum.period];
      } else if (hasSingle) {
        this.paymentMethodSelected = [paymentMethodEnum.single];
      }
    },
    calcSkus(ageListStringify) {
      const ageList = ageListStringify.map((item) => JSON.parse(item));
      console.log(ageList);
      // 重新计算所有sku
      let skus = [];
      this.paymentMethodSelected.forEach((paymentMethod) => {
        ageList.forEach((item) => {
          skus.push(
            {
              ...item,
              paymentMethod: paymentMethod,
            } || {},
          );
        });
      });
      return sortPmsSkuPriceByAge(skus);
    },
    handleAddSkuAge() {
      this.$refs.ageFormRef.validate((valid) => {
        if (valid) {
          const ageConflictIndex = this.checkAgeValid({
            startPurchaseAge: this.ageForm.startPurchaseAge,
            startUnit: this.ageForm.startUnit,
            endPurchaseAge: this.ageForm.endPurchaseAge,
            endUnit: this.ageForm.endUnit,
          });
          if (ageConflictIndex === -1) {
            this.ageList = sortPmsSkuPriceByAge([
              ...this.ageList,
              {
                startPurchaseAge: this.ageForm.startPurchaseAge,
                startUnit: this.ageForm.startUnit,
                endPurchaseAge: this.ageForm.endPurchaseAge,
                endUnit: this.ageForm.endUnit,
              },
            ]);
            this.ageListSelection.push(
              JSON.stringify({
                startPurchaseAge: this.ageForm.startPurchaseAge,
                startUnit: this.ageForm.startUnit,
                endPurchaseAge: this.ageForm.endPurchaseAge,
                endUnit: this.ageForm.endUnit,
              }),
            );
            this.handleUpdateSkus();
          } else if (ageConflictIndex >= 0) {
            const ageConflictItem = this.ageList[ageConflictIndex];

            const ageConflictStr = this.formatAgeRange(ageConflictItem);
            this.$message({
              message: `年龄冲突，您已经设置过${ageConflictStr}`,
              type: "warning",
            });
          }
          this.ageDialogVisible = false;
          this.ageForm = {
            ...initAgeForm,
          };
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    checkAgeValid({ startPurchaseAge, startUnit, endPurchaseAge, endUnit }) {
      const ageList = this.ageList || [];

      if (startPurchaseAge < 0 || endPurchaseAge < 0) {
        this.$message.error("年龄不能为负数");
        return -2; // -2表示无效输入
      }
      const startInYears = convertToYears(startPurchaseAge, startUnit);
      const endInYears = convertToYears(endPurchaseAge, endUnit);
      console.log(startInYears, endInYears);

      if (startInYears >= endInYears) {
        this.$message.error("起始年龄必须早于结束年龄");
        return -2;
      }

      for (let i = 0; i < ageList.length; i++) {
        const item = ageList[i];
        const itemStartInYears = convertToYears(
          item.startPurchaseAge,
          item.startUnit,
        );
        const itemEndInYears = convertToYears(
          item.endPurchaseAge,
          item.endUnit,
        );

        // 检查是否有交集
        if (
          (startInYears < itemEndInYears && endInYears > itemStartInYears) || // 当前区间与已有区间交叉
          (itemStartInYears < endInYears && itemEndInYears > startInYears) // 已有区间与当前区间交叉
        ) {
          return i;
        }
      }
      return -1;
    },
    handleUpdateSkus() {
      this.$emit("update-sku", this.calcSkus(this.ageListSelection));
    },

    handleDeletePriceItem(index) {
      this.$emit("deleteSkuPrice", index);
    },

    handleSave() {
      // 检查购买价格是否填写
      const isValid = this.checkPrice();
      if (isValid) {
        this.$emit("finishCommit", this.isEdit);
      }
    },
    checkPrice() {
      // 检查价格是否合法
      let isValid = true;
      for (let i = 0; i < this.value.pmsSkuPrices.length; i++) {
        const pmsSkuItem = this.value.pmsSkuPrices[i];
        if (!pmsSkuItem.price || pmsSkuItem.price < 0) {
          isValid = false;
          this.$refs.ageTableRef.setCurrentRow(pmsSkuItem);
          console.log(this.$refs.ageTableRef, pmsSkuItem);
          this.$message.error("价格填写错误");
          break;
        }
      }
      return isValid;
    },
    handleDeleteAgeItem(index, row) {
      // 从 ageList 中删除对应的年龄段
      this.ageList.splice(index, 1);

      // 从 ageListSelection 中移除对应的选中项
      const rowString = JSON.stringify(row);
      this.ageListSelection = this.ageListSelection.filter(
        (item) => item !== rowString,
      );

      // 更新价格表格数据
      this.handleUpdateSkus();

      this.$message({
        message: "删除成功",
        type: "success",
      });
    },
  },
};
</script>

<style scoped lang="scss">
.littleMarginLeft {
  margin-left: 10px;
}

.cardBg {
  background: #f8f9fc;
}
</style>
